package New;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: 叶子
 * @date: 2022/06/07 22:11
 * 线程池场景下，每次用完了ThreadLocal变量，需要手动调用remove方法remove掉ThreadLocal
 **/
class MyData{
    ThreadLocal<Integer> threadLocalField = ThreadLocal.withInitial(()->0);
    public void add(){
        threadLocalField.set(1+threadLocalField.get());
    }
}
public class ThreadLocalDemo2 {
    public static void main(String[] args) {
        MyData myData = new MyData();
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        try {
            for (int i = 1; i <=10; i++) {
                threadPool.submit(()->{
                    try {
                        Integer beforeInt = myData.threadLocalField.get();
                        myData.add();
                        Integer afterInt = myData.threadLocalField.get();
                        System.out.println(Thread.currentThread().getName()+"\t"+"beforeInt:"+beforeInt+"\tafterInt:"+afterInt);
                    } finally {
                        myData.threadLocalField.remove();
                    }
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
    }
}